<?php
namespace Home\Controller;
use Think\Controller;
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';

class CourtesyController extends Controller {
    public function card_list()
    {
    	$type_id= I('get.type_id','1');

    	$types = D('CardType');
    	$card_type = $types->select();
    	//$card_type = $types->get_cardtype();

    	$cards = D('Courtesy');
        $card_list = $cards->get_cardlist($type_id);
        
        $this->assign('card_type',$card_type);
        $this->assign('card_list',$card_list);
    	$this->display();
    }

    public function card_info()
    {
    	$card_id= I('get.card_id','');

    	$cards = D('Courtesy');
        $card_info = $cards->get_cardinfo($card_id);
        
        $this->assign('card_info',$card_info);

    	$this->display();
    }

    //立即兑换
    public function ex_change()
    {
        $card_id= I('get.cid','');
        $type_id= I('get.tid',''); 
        $user_id = session('user_id') ? session('user_id') : 1;//暂时代替，做微信登录时修改
        if($user_id)
        {
            //查询所需积分
            $cards = D('CardList');
            $card_integral = intval($cards->where('card_id='.$card_id)->getField('card_integral'));

            //查询会员目前积分
            $user = D('Users');
            $user_points = intval($user->where('user_id='.$user_id)->getField('user_points'));

            if($user_points > $card_integral)
            {
                //对card_nums 减-1
                $cards->where('card_id='.$card_id)->setDec('card_nums');

                //更新积分
                $data['user_points'] = $user_points - $card_integral;
                $user->where('user_id='.$user_id)->save($data);
                
                //积分记录
                $log['user_id']       = $user_id;
                $log['card_id']       = $card_id;
                $log['user_points']   = '-'.$card_integral;
                $log['log_time']      = time();
                $log['log_text']      = "兑换礼券";
                $potlog = D('PointsLog');
                $potlog->add($log);

                //添加到am_user_card表
                //is_status有效券 == 1 已使用 == 2 已失效 == 3
                $val['card_id']    = $card_id;
                $val['user_id']    = $user_id;
                $val['is_status']  = 1;
                $val['type_id']    = $type_id;

                $user = D('UserCard');
                $result = $user->add($val);
                if($result)
                {
                    $this->success('兑换成功，请到会员中心查看',U('UserCenter/member'),3);
                }
                
            }
            else
            {
                $this->error('您目前积分不够兑换~',U('Courtesy/card_list'),3);
            }

        }
        else
        {
            $this->error('请先登录',U('Index/index'),3);
        }
    }
}